import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';
import { ReminderSettings } from '../types/Reminder';
import StorageService from './storage';

// 配置通知处理
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

/**
 * 通知服务 - 处理本地通知的调度与管理
 */
export const NotificationService = {
  /**
   * 请求通知权限
   */
  async requestPermissions(): Promise<boolean> {
    const { status } = await Notifications.requestPermissionsAsync();
    return status === 'granted';
  },

  /**
   * 检查通知权限状态
   */
  async checkPermissions(): Promise<boolean> {
    const { status } = await Notifications.getPermissionsAsync();
    return status === 'granted';
  },

  /**
   * 调度提醒通知
   */
  async scheduleReminderNotification(reminder: ReminderSettings): Promise<string> {
    try {
      // 检查权限
      const hasPermission = await this.checkPermissions();
      if (!hasPermission) {
        throw new Error('Notification permissions not granted');
      }

      // 获取应用设置
      const appSettings = await StorageService.getAppSettings();

      // 解析时间字符串为分钟数
      const [hours, minutes] = reminder.time.split(':').map(Number);
      const now = new Date();
      const notificationTime = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        hours,
        minutes
      );

      // 如果时间已过今天，则安排到明天
      if (notificationTime < now) {
        notificationTime.setDate(notificationTime.getDate() + 1);
      }

      // 计算提前提醒时间
      const triggerTime = new Date(notificationTime);
      triggerTime.setMinutes(triggerTime.getMinutes() - reminder.advanceReminder);

      // 创建通知内容
      const content: Notifications.NotificationContentInput = {
        title: '下班打卡提醒',
        body: `${reminder.title} - ${reminder.time}`,
        sound: appSettings.notificationSound === 'default' ? 'default' : appSettings.notificationSound,
        vibrate: appSettings.vibrationEnabled ? [0, 250, 250, 250] : false,
        data: {
          type: 'reminder',
          reminderId: reminder.id,
          snoozeEnabled: reminder.snoozeEnabled,
          snoozeInterval: reminder.snoozeInterval,
        },
      };

      // 设置重复规则
      const repeatTrigger = reminder.repeat
        ? {
            hour: hours,
            minute: minutes,
            repeats: true,
            ...(reminder.repeatDays.length > 0 && {
              weekday: reminder.repeatDays,
            }),
          }
        : undefined;

      // 调度通知
      const trigger: Notifications.NotificationTriggerInput = repeatTrigger
        ? { ...repeatTrigger }
        : { date: triggerTime };

      const identifier = await Notifications.scheduleNotificationAsync({
        content,
        trigger,
      });

      return identifier;
    } catch (error) {
      console.error('Failed to schedule notification:', error);
      throw error;
    }
  },

  /**
   * 取消特定通知
   */
  async cancelNotification(identifier: string): Promise<void> {
    try {
      await Notifications.cancelScheduledNotificationAsync(identifier);
    } catch (error) {
      console.error('Failed to cancel notification:', error);
      throw error;
    }
  },

  /**
   * 取消所有通知
   */
  async cancelAllNotifications(): Promise<void> {
    try {
      await Notifications.cancelAllScheduledNotificationsAsync();
    } catch (error) {
      console.error('Failed to cancel all notifications:', error);
      throw error;
    }
  },

  /**
   * 处理稍后提醒
   */
  async handleSnooze(reminder: ReminderSettings): Promise<string> {
    try {
      // 创建延迟后的触发时间
      const now = new Date();
      const snoozeTime = new Date(now);
      snoozeTime.setMinutes(now.getMinutes() + reminder.snoozeInterval);

      // 创建通知内容
      const appSettings = await StorageService.getAppSettings();
      const content: Notifications.NotificationContentInput = {
        title: '下班打卡提醒 (稍后提醒)',
        body: `${reminder.title} - ${reminder.time}`,
        sound: appSettings.notificationSound === 'default' ? 'default' : appSettings.notificationSound,
        vibrate: appSettings.vibrationEnabled ? [0, 250, 250, 250] : false,
        data: {
          type: 'reminder',
          reminderId: reminder.id,
          snoozeEnabled: reminder.snoozeEnabled,
          snoozeInterval: reminder.snoozeInterval,
        },
      };

      // 调度稍后提醒
      const identifier = await Notifications.scheduleNotificationAsync({
        content,
        trigger: { date: snoozeTime },
      });

      return identifier;
    } catch (error) {
      console.error('Failed to handle snooze:', error);
      throw error;
    }
  },
};

export default NotificationService;